/**
 *  * Created by wz on 2017/9/19
 *  * <p/>
 *  * Copyright (c) 2015-2015
 *  * Apache License
 *  * Version 2.0, January 2004
 *  * http://www.apache.org/licenses/
 *  
 */
package com.huirui.controller;

import com.huirui.entity.Identity;
import com.huirui.entity.User;
import com.huirui.form.UserForm;
import com.huirui.service.IdentityService;
import com.huirui.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.util.List;

@RestController
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    IdentityService identityService;

    @RequestMapping(value = "/showSelect", method = RequestMethod.GET)
    public List<Identity> showIndex() {

        return identityService.listIdentity(); //获取身份类型列表

    }

    @RequestMapping(value = "/userLogin", method = RequestMethod.POST)
    public boolean login(@PathParam("user") User user, HttpServletRequest request) {

        boolean flag = false;
        HttpSession session = request.getSession();
        UserForm userForm = null;

        User u;
        if (user.validate()) { //判断字段非空
            u = userService.loginWithIdentity(user); //判断用户是否存在
            if (u != null){ //存在则将用户信息存入session
                flag = true;
                userForm = new UserForm(u.getIdentity().getIdentityName(),u.getUsername());
            }
        }

        System.out.println(userForm);
        session.setAttribute("userForm",userForm);
        return flag;
    }


    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public UserForm userForm(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        UserForm userForm = null;
        if (session != null) {
            Object obj = session.getAttribute("userForm");
            if (obj != null) {
                userForm = (UserForm) obj;
            }
        }
        return userForm;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public void logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);

        if (session != null) {
            session.removeAttribute("userForm");
        }
    }

}